package me.shiqiang.im.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.tst.common.exception.MicroServiceException;
import com.tst.common.returnobj.ReturnObjCode;
import me.shiqiang.im.enums.MessageCType;
import me.shiqiang.im.microservice.AppNotificationMicroService;
import me.shiqiang.im.microservice.returnobj.NotifyFinReturnObj;
import me.shiqiang.im.msg.MsgBody;
import me.shiqiang.im.msg.NewMsg;
import me.shiqiang.im.service.GroupService;
import me.shiqiang.im.utils.JsonUtils;
import me.shiqiang.im.utils.AppNotifyUtil;
import me.shiqiang.im.utils.CountDownTimer;
import me.shiqiang.im.vo.AppNotificationVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by John on 2018/1/22
 */
@Component("NotificationsConsumer")
public class NotificationsConsumer implements MessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    static ConcurrentHashMap<Long, CountDownTimer> map = new ConcurrentHashMap<>();


    @Autowired
    private AppNotificationMicroService appNotificationMicroService;

    @Autowired
    private GroupService groupService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String msgBodyStr = new String(message.getBody());
        AppNotificationVo notificationVo = new AppNotificationVo();
        logger.info("msgBodyStr= {}", msgBodyStr);
        AppNotifyUtil appNotifyUtil = new AppNotifyUtil();
        try {
            NewMsg newMsg = JsonUtils.getInstance().fromJson(msgBodyStr, NewMsg.class);
            logger.info("通知被消费" + newMsg.toString());
            MsgBody msgBody = newMsg.getMsgBody();

//            notificationVo.setPushType("MESSAGE");
            notificationVo.setPushType("NOTICE");
            notificationVo.setTarget("ACCOUNT");
            notificationVo.setDeviceType("ALL");
            Map extraParams = new HashMap<>();
            extraParams.put("category", 2);
            notificationVo.setExtParameters(extraParams);
            notificationVo.setTargetValue(String.valueOf(newMsg.getUserId()));
            if (Objects.equals(newMsg.getUserId(), msgBody.getFrom())) {
                return Action.CommitMessage;
            }
            if (msgBody.getcType() == Integer.parseInt(MessageCType.GROUP)) {
                if (msgBody.getAt().equals(1)) {
                    notificationVo.setTitle("群消息");
                    notificationVo.setBody(String.format("%s在群聊中@了你",msgBody.getFromName()));
                    try {
                        logger.info(JsonUtils.getInstance().toJson(notificationVo));
                        NotifyFinReturnObj returnObj = appNotificationMicroService.appNotification(notificationVo);
                        if (!ReturnObjCode.SUCCESS.getCode().equals(returnObj.getCode())) {
                            logger.warn("APP通知微服务服务返回失败,response:{}", returnObj.toString());
                            throw new MicroServiceException(returnObj.getMsg());
                        }
                    } catch (Exception e) {
                        logger.error(String.format("消息通知失败,msg:%s", e));
                    }
                }else {
                    if (groupService.isNoDisturb(newMsg.getUserId(), msgBody.getTo(), 2)) {
                        logger.info("已设置免打扰");
                        return Action.CommitMessage;
                    }
                    notificationVo.setTitle("群消息");

                    Long userId = newMsg.getUserId();
                    if (map.get(userId) != null) {
                        CountDownTimer countDownTimer = map.get(userId);
                        countDownTimer.increment();
                        return Action.CommitMessage;
                    } else {
                        CountDownTimer countDownTimer = new CountDownTimer(5000, 5000) {
                            @Override
                            public void onTick(long millisUntilFinished) {

                            }

                            @Override
                            public void onFinish() {
                                Long count = this.getCount();
                                map.remove(userId);
                                if (count == 1) {
                                    appNotifyUtil.translateMtype(msgBody, notificationVo);
                                } else {
                                    notificationVo.setBody(String.format("收到%s条群消息", String.valueOf(count)));
                                }
                                try {
                                    logger.info(JsonUtils.getInstance().toJson(notificationVo));
                                    NotifyFinReturnObj returnObj = appNotificationMicroService.appNotification(notificationVo);
                                    if (!ReturnObjCode.SUCCESS.getCode().equals(returnObj.getCode())) {
                                        logger.warn("APP通知微服务服务返回失败,response:{}", returnObj.toString());
                                        throw new MicroServiceException(returnObj.getMsg());
                                    }
                                } catch (Exception e) {
                                    logger.error(String.format("消息通知失败,msg:%s", e));
                                }
                            }
                        }.start();
                        map.put(userId, countDownTimer);
                        countDownTimer.increment();

                    }
                }

                //带来的todo: 客户端屏蔽功能，回到最久远未读消息

            } else {
                notificationVo.setTitle(msgBody.getFromName());
                appNotifyUtil.translateMtype(msgBody, notificationVo);
                try {
                    logger.info(JsonUtils.getInstance().toJson(notificationVo));
                    NotifyFinReturnObj returnObj = appNotificationMicroService.appNotification(notificationVo);
                    if (!ReturnObjCode.SUCCESS.getCode().equals(returnObj.getCode())) {
                        logger.warn("APP通知微服务服务返回失败,response:{}", returnObj.toString());
                        throw new MicroServiceException(returnObj.getMsg());
                    }
                    return Action.CommitMessage;
                } catch (Exception e) {
                    logger.error(String.format("消息通知失败,msg:%s", e));
                    e.printStackTrace();
                    return Action.ReconsumeLater;
                }
            }
        } catch (Exception e) {
            logger.error("e {}", e);
        }

        return Action.CommitMessage;
    }

}
